import http from '@ohos.net.http';
import Food from '../modle/Food';
import PreferenceUtil from './PreferencesUtil'
import { preferences } from '@kit.ArkData';
import LoginResponse from '../modle/LoginResponse';
import OrderBean from '../modle/OrderBean';
import Toast from './Toast';

class ApiUtil {
  checkUserNameExists(userName: string) {
    throw new Error('Method not implemented.');
  }
  private httpRequest = http.createHttp();
  // private baseUrl = "http://127.0.0.1:8080/";
  //这里填入你电脑的IP地址，windows使用命令ipconfig查看
  private baseUrl = "http://192.168.88.1:8081/";

  /*getRequest() {
    this.httpRequest.request(
      this.baseUrl,
      {
        method: http.RequestMethod.GET,
        // 可根据需要添加请求头
        header: {
          'Content-Type': 'application/json'
        }
      }, (err, data) => {
      if (!err) {
        console.info("Request success, data: " + data.result.toString());
        // 在这里处理返回的数据，例如解析 JSON 数据
        if (data.responseCode === 200) {
          let responseData = JSON.parse(data.result.toString());
          console.info("Parsed data: " + JSON.stringify(responseData));
        }
      } else {
        console.error("Request failed, error: " + JSON.stringify(err));
      }
    }
    );
  }*/

  /*postRequest() {
    this.httpRequest.request(
      this.baseUrl,
      {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json'
        },
        // 对于 POST 请求，可以添加请求体
        extraData: JSON.stringify({
          key1: 'value1',
          key2: 'value2'
        })
      }, (err, data) => {
      if (!err) {
        console.info("Request success, data: " + data.result.toString());
      } else {
        console.error("Request failed, error: " + JSON.stringify(err));
      }
    }
    );
  }*/

  private doPost(
    path: string,
    paramsObj: object,
    sucessCallBack: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.httpRequest.request(
      this.baseUrl + path,
      {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json'
        },
        // 对于 POST 请求，可以添加请求体
        extraData: JSON.stringify(paramsObj)
      }, (err, data) => {
      endCallBack?.()
      if (!err) {
        let resStr = data.result.toString()
        let resObj = data.result
        console.info("zhu post Request success, data: " + resStr);
        sucessCallBack(resObj)
      } else {
        console.error("zhu post Request failed, error: " + JSON.stringify(err));
        Toast.show('post请求错误=' + err.message)
      }
    }
    );
  }

  private doGet(
    path: string,
    paramsObj: object,
    sucessCallBack: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.httpRequest.request(
      this.baseUrl + path,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        },
        // 对于 POST 请求，可以添加请求体
        extraData: JSON.stringify(paramsObj)
      }, (err, data) => {
      endCallBack?.()
      if (!err) {
        let resStr = data.result.toString()
        let resObj = data.result
        console.info("zhu get Request success, data: " + resStr);
        sucessCallBack(resObj)
      } else {
        console.error("zhu get Request failed, error: " + JSON.stringify(err));
        Toast.show('get请求错误=' + err.message)
      }
    }
    );
  }

  public login(
    paramsObj: object,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('user_info/login', paramsObj, (res: Object) => {
      try {
        console.info("zhu login success, data: " + res);
        let obj: any = JSON.parse(res.toString())
        let id = obj.userInfo.id
        PreferenceUtil.putPreferenceValue('user_id', id)
        callback(res)
      } catch (e) {
        console.error("zhu login catch, e= " + e);
      }
    }, endCallBack)
  }

  public register(
    paramsObj: object,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('user_info/regist', paramsObj, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public getHomeData(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doGet('home_data/get', null, (res: Object) => {
      try {
        console.info("zhu home success, data: " + res);
        callback(res)
      } catch (e) {
        console.error("zhu home catch, e= " + e);
      }
    }, endCallBack)
  }

  public getCateList(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doGet('cate_list/get', null, (res: Object) => {
      try {
        console.info("zhu getCateList success, data: " + res);
        callback(res)
      } catch (e) {
        console.error("zhu getCateList catch, e= " + e);
      }
    }, endCallBack)
  }

  public async cartAdd(
    paramsObj: Food,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    paramsObj.user_id = v2 as number
    this.doPost('cart/add', paramsObj, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public cartDelete(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('cart/delete', {
      id: id
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public cartBatchDelete(
    idList: number[],
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('cart/batchDelete', {
      idList: idList
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public async cartQueryAll(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    let user_id = v2 as number
    this.doPost('cart/queryAll', {
      user_id: user_id
    }, (res: Object) => {
      console.info("zhu cartQueryAll success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public async orderAdd(
    paramsObj: OrderBean,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    paramsObj.user_id = v2 as number
    this.doPost('order/add', paramsObj, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public async orderQueryAll(
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    let v2: preferences.ValueType = await PreferenceUtil.getPreferenceValue('user_id', '')
    let user_id = v2 as number
    this.doPost('order/queryAll', {
      user_id: user_id
    }, (res: Object) => {
      console.info("zhu cartQueryAll success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public orderDelete(
    id: number,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    this.doPost('order/delete', {
      id: id
    }, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

  public orderUpdate(
    item: OrderBean,
    callback: CallableFunction,
    endCallBack?: CallableFunction
  ) {
    item.state = 1
    this.doPost('order/updateState', item, (res: Object) => {
      console.info("zhu register success, data: " + res);
      callback(res)
    }, endCallBack)
  }

}

let apiUtil = new ApiUtil()

export default apiUtil as ApiUtil